package org.mathig.poker.table;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.mathig.poker.PlayerWrapper;

public class PlayerAmount {

	private Map<PlayerWrapper, Integer> values = new HashMap<PlayerWrapper, Integer>();

	@Override
	public String toString() {
		return getTotal() + " " + values;
	}

	public void set(PlayerWrapper player, int value) {
		values.put(player, value);
	}

	public Set<PlayerWrapper> getPlayers() {
		return values.keySet();
	}

	public void add(PlayerWrapper player, int value) {
		int old = get(player);
		values.put(player, new Integer(old + value));
	}

	public int remove(PlayerWrapper player) {
		int old = get(player);
		values.remove(player);
		return old;
	}

	public int removeTotal(PlayerWrapper player) {
		int old = get(player);
		if (old == 0)
			throw new IllegalArgumentException("player " + player + " is broken");
		values.remove(player);
		return old;
	}

	public void remove(PlayerWrapper player, int value) {
		int old = get(player);
		if (old == 0)
			return;
		if (value > old)
			value = old;
		values.put(player, new Integer(old - value));
	}

	/**
	 * Remove same amount from players.<br>
	 * If a player has not enough, full value of this player is summed.<br>
	 * 
	 * @param players
	 * @param value
	 * @return total amount of values removed (may be < value * players.size())
	 */
	public int removeAll(List<PlayerWrapper> players, int value) {
		int removed = 0;
		for (PlayerWrapper player : players) {
			int min = Math.min(value, get(player));
			removed += min;
			remove(player, min);
		}
		return removed;
	}

	public int removeAllOthers(List<PlayerWrapper> players) {
		int removed = 0;
		List<PlayerWrapper> keys = new ArrayList<PlayerWrapper>(values.keySet());
		for (PlayerWrapper player : keys) {
			if (!players.contains(player)) {
				int bet = values.remove(player);
				removed += bet;
			}
		}
		return removed;
	}

	public int removeAll(int value) {
		int removed = 0;
		for (PlayerWrapper player : values.keySet()) {
			int min = Math.min(value, get(player));
			if (min > 0) {
				removed += min;
				remove(player, min);
			}
		}
		return removed;
	}

	public int getTotal() {
		int pot = 0;
		for (PlayerWrapper player : values.keySet())
			pot += values.get(player);
		return pot;
	}

	public int getMax() {
		int max = 0;
		for (PlayerWrapper player : values.keySet())
			if (get(player) > max)
				max = get(player);
		return max;
	}

	public int getMin(List<PlayerWrapper> players) {
		int min = getMax();
		for (PlayerWrapper player : players)
			if (get(player) > 0 && get(player) < min)
				min = get(player);
		return min;
	}

	public int get(PlayerWrapper player) {
		Integer bet = values.get(player);
		return bet == null ? 0 : bet;
	}

}
